import { addResizeListener, removeResizeListener } from 'element-ui/src/utils/resize-event';

// 动态计算 bottomOffset 的值
const calculateBottomOffset = () => {
  const width = window.innerWidth;
  const maxWidth = 1920;  // 参考的最大宽度
  const maxOffset = 30;   // 最大宽度时的bottomOffset
  const minOffset = 10;   // 最小宽度时的bottomOffset

  if (width >= maxWidth) {
    return maxOffset;
  } else if (width <= 800) {
    return minOffset;
  } else {
    const offsetRange = maxOffset - minOffset;
    const widthRange = maxWidth - 800;
    return minOffset + ((width - 800) * offsetRange) / widthRange;
  }
};

// 计算指定元素的总高度
const calculateElementsHeight = (selectors) => {
  return selectors.reduce((totalHeight, selector) => {
    const element = document.querySelector(selector);
    if (element) {
      totalHeight += element.offsetHeight;
    }
    return totalHeight;
  }, 0);
};

// 设置表格高度
const doResize = async (el, binding, vnode) => {
  const { componentInstance: $table } = await vnode;
  const { value } = binding;
  const bottomOffset = (value && value.bottomOffset) || calculateBottomOffset();
  const additionalSelectors = value && value.additionalSelectors || [];

  if (!$table) return;

  // 计算指定其他元素的总高度
  const otherElementsHeight = calculateElementsHeight(additionalSelectors);

  // 计算表格高度并设置
  const height = window.innerHeight - otherElementsHeight - bottomOffset;
  $table.layout.setHeight(height);
  $table.doLayout();
};

export default {
  // 初始化设置
  bind(el, binding, vnode) {
    el.resizeListener = async () => {
      await doResize(el, binding, vnode);
    };
    addResizeListener(window.document.body, el.resizeListener);
  },
  // 绑定默认高度
  async inserted(el, binding, vnode) {
    await doResize(el, binding, vnode);
  },
  // 销毁时设置
  unbind(el) {
    removeResizeListener(el, el.resizeListener);
  }
};
